package com.feonix.common.view.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.feonix.common.permission.IPermissionCheckor;
import com.feonix.common.util.FreemarkerUtil;
import com.feonix.common.util.JsonUtil;
import com.feonix.common.util.StringUtil;
import com.feonix.common.view.menu.Menu;
import com.feonix.common.view.menu.MenuItem;

public class Menu {
	private List<MenuItem> rootMenuItems = new ArrayList<MenuItem>();

	private Map<String, List<MenuItem>> subMenuItems = new HashMap<String, List<MenuItem>> ();

	public static Menu getInstance() {
		return new Menu();
	}

	public void addMenuItem(MenuItem menuItem) {
		if (menuItem.hasRight()) {
			String pid = menuItem.getPid();
			if (StringUtil.isEmpty(pid)) {
				this.rootMenuItems.add(menuItem);
			} else {
				List<MenuItem> subMenuItemList = this.subMenuItems.get(pid);
				if (subMenuItemList == null) {
					subMenuItemList = new ArrayList<MenuItem>();
					this.subMenuItems.put(pid, subMenuItemList);
				}
				subMenuItemList.add(menuItem);
			}
		}
	}

	public void addMenuItem(MenuItem menuItem, IPermissionCheckor<MenuItem> iPermissionCheckor) {
		if (iPermissionCheckor.check(menuItem)) {
			String str = menuItem.getPid();
			if (StringUtil.isEmpty(str)) {
				this.rootMenuItems.add(menuItem);
			} else {
				List<MenuItem> menuItems = this.subMenuItems.get(str);
				if (menuItems == null) {
					menuItems = new ArrayList<MenuItem>();
					this.subMenuItems.put(str, menuItems);
				}
				menuItems.add(menuItem);
			}
		}
	}

	public String parse() {
		organization();
		String str = FreemarkerUtil.processFTL("menu.ftl", "top_menus", this.rootMenuItems);
		return str;
	}

	private void organization() {
		List<MenuItem> subMenuItems = null;
		for (MenuItem menuItem : this.rootMenuItems) {
			subMenuItems = this.subMenuItems.get(menuItem.getId());
			menuItem.addSubMenuItem(subMenuItems);
			organization(subMenuItems);
		}
	}

	private void organization(List<MenuItem> subMenuItems) {
		if (subMenuItems == null) {
			return;
		}
		List<MenuItem> menuItemList = null;
		for (MenuItem menuItem : subMenuItems) {
			menuItemList = this.subMenuItems.get(menuItem.getId());
			menuItem.addSubMenuItem(menuItemList);
			organization(menuItemList);
		}
	}
}
